// pages/goodsDetail/goodsDetail.js
import {
  Get,
  Post,
  JsonPost
} from "../../utils/request.js"
import Common from "../../utils/common.js"
var Time
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 详情参数
    detailInfo: {
      goods_id: 25,
      lat: null,
      lng: null,
      page: 1
    },
    // 轮播图
    background: [],
    // 基本信息
    baseInfo: {},
    // 规格列表
    sku: [],
    // 选中规格
    checkSku: {},
    // 三条评价
    three: [],
    // 商品详情
    goodsDetail: '',
    // 完整评价
    intactEva: [],
    // 登录状态
    loginStatus: 0,
    phoneNum: '',
    wpxIos: false,
    moadelShow: false,
    actionTab:1,
    //已触底
    chudi: false,
    jiazai: false,
    // table栏与顶部的距离 
    topheight: 0,
    // 是否吸顶
    onTop: false,
    // 是否选过规格
    goPay: false,
    open: false,
    // 跳转页面 1:购物车 2:支付 3:拼单
    goPage: 1,
    // 规格详情
    specInfo: {},
    // 拼单id
    pingou_id: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#ffffff'
    })
    let that = this
    // 监测table栏滚到顶部
    wx.createSelectorQuery().selectAll('.wpxTable').boundingClientRect(function (rect) {
      that.setData({
        topheight: rect[0].top
      })
    }).exec();
    let str = "detailInfo.goods_id"
    this.setData({
      wpxIos: getApp().globalData.wpxIos,
      [str]: options.goods_id
    })
    if (options.q) {
      that.setData({
        [str]: decodeURIComponent(options.q).split("?goods_id=")[1]
      })
    }else if(options.scene){
      that.setData({
        [str]: decodeURIComponent(options.scene).split("?goods_id=")[1].split("?uid=")[0],
      })
    }else{
      that.setData({
        [str]: options.goods_id
      })
    }
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        let str = "detailInfo.lng"
        let str1 = "detailInfo.lat"
        that.setData({
          [str]: res.longitude,
          [str1]: res.latitude,
        })
      }
    })
    if (getApp().globalData.login) {
      this.setData({
        loginStatus: 1
      })
      // if (wx.getStorageSync('getCall')) {
      //   this.setData({
      //     loginStatus: 2,
      //     phoneNum: wx.getStorageSync('phoneNum')
      //   })
      // } else {
      //   this.setData({
      //     loginStatus: 1
      //   })
      // }
    }
    // if (this.data.loginStatus != 2) {
    //   this.getCode()
    //   let that = this
    //   Time = setInterval(function () {
    //     that.getCode()
    //   }, 270000)
    // }
    that.getCollage()
    this.getEvaluate()
    this.selectComponent("#formatBox").getInfo()
    that.getDetail()
  },

  // 点击查看图片
  clickImg(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.url, // 当前显示图片的http链接
      urls: typeof (e.currentTarget.dataset.arr) == 'object' ? e.currentTarget.dataset.arr : [e.currentTarget.dataset.arr] // 需要预览的图片http链接列表
    })
  },

  // 获取商品详情
  getDetail() {
    let data = this.data.detailInfo
    JsonPost('goods/detail', data).then(res => {
      let imgArr = [res.data.goods_video, ...res.data.goods_banner]
      let fieldDetail = res.data.content || ''
      this.setData({
        background: imgArr,
        baseInfo: res.data,
        goodsDetail: fieldDetail.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display: block;margin: 20rpx auto;" ').replace(/<p>/ig, '<p class="p_class">')
      })
    })
  },

  // 获取拼团
  getCollage() {
    let data = this.data.detailInfo
    JsonPost('collage/list', data).then(res => {
      this.setData({
        collageInfo: res.data,
      })
    })
  },


  // 获取评价详情
  getEvaluate() {
    let wpxNum = this.data.intactEva.length
    let data = this.data.detailInfo
    JsonPost('goods/evaluate', data).then(res => {
      if (!res.data) {
        this.setData({
          chudi: true,
          jiazai: false
        })
        return
      }
      let arr = res.data.data
      res.data.data.forEach((ele, index) => {
        arr[index].createWTime = Common.formatTimestamp(ele.create_time * 1000, 'yyyy/MM/dd')
      });
      let arr1 = this.data.intactEva
      this.setData({
        intactEva: [...arr1, ...arr]
      })
      if (wpxNum == this.data.intactEva.length) {
        this.setData({
          chudi: true,
          jiazai: false
        })
      } else {
        this.setData({
          chudi: false
        })
      }
    })
  },

  // 获取code
  getCode() {
    console.log("getCode")
    wx.login({
      success: loginInfo => {
        this.setData({
          code: loginInfo.code
        })
      }
    })
  },


  // 获取用户信息
  bindGetUserInfo(e) {
    getApp().ttClogin()
    getApp().userInfoReadyCallback = () => {
      this.setData({
        loginStatus: 1
      })
      this.goPay({
        'currentTarget': {
          'dataset': {
            'page': e.currentTarget.dataset.page
          }
        }
      })
      // this.getCode()
      console.log(getApp().globalData.userInfo, 'userInfoReadyCallback')
    }
  },

  // 获取用户手机号
  getPhoneNumber(e) {
    if (e.detail.errMsg !== "getPhoneNumber:ok") {
      return;
    }
    let Data = {
      encrypteData: encodeURIComponent(e.detail.encryptedData),
      iv: e.detail.iv,
      code: this.data.code,
    }
    Post('api/getPhone', Data).then(res => {
      if (res.data) {
        clearInterval(Time)
        wx.setStorageSync('getCall', true)
        wx.setStorageSync('phoneNum', res.data.phoneNumber)
        this.setData({
          loginStatus: 2,
          phoneNum: wx.getStorageSync('phoneNum')
        })
        this.goPay()
      }
    })
  },

  // 打开模态框
  openMoadel() {
    this.setData({
      open: true,
      // moadelShow: true,
    })
  },

  // 关闭模态框
  closMoadel() {
    this.setData({
      moadelShow: false
    })
  },


  // 选择tab
  selectionTab(e) {
    this.setData({
      actionTab: e.currentTarget.dataset.index
    })
  },

  // 跳转至支付页
  goPay(e) {
    this.setData({
      goPage: e.currentTarget.dataset.page,
      open: true,
      pingou_id: e.currentTarget.dataset.id
    })
  },

  share() {
    this.selectComponent("#vposter").creat()
  },

  // 拨打手机号
  copyPhone() {
    wx.makePhoneCall({
      phoneNumber: this.data.baseInfo.mobile
    })
  },

  // 复制微信号
  copyWx() {
    wx.setClipboardData({
      data: this.data.baseInfo.weChat,
      success(res) {

      }
    })
  },


  // 前往地图导航
  goMap() {
    wx.openLocation({
      latitude: Number(this.data.baseInfo.store.ypoint), //维度
      longitude: Number(this.data.baseInfo.store.xpoint), //经度
      name: this.data.baseInfo.store.name, //目的地定位名称
      scale: 15, //缩放比例
    })
  },

  // 添加收藏
  collect(){
    JsonPost('goods/collection',{'goods_id':this.data.detailInfo.goods_id}).then(res=>{
      if (res.code==0) {
        wx.showToast({
          title: '已加入收藏',
          icon: 'none',
          duration: 2000
        })
        let str="baseInfo.is_collection"
        this.setData({
          [str]:1
        })
      }
    })
  },


  goCart() {
    wx.switchTab({
      url: '/pages/shopCart/shopCart',
    })
  },

  goKan() {
    wx.navigateTo({
      url: '/pages/kanjPage/kanjPage?goods_id='+this.data.detailInfo.goods_id,
    })
  },
  goJisuan() {
    wx.navigateTo({
      url: '/pages/jisuanBrick/jisuanBrick?price=' + this.data.baseInfo.shop_price,
    })
  },

  _getGuiGObj(e) {
    this.setData({
      specInfo: e.detail
    })
    if (this.data.goPage == 1) {
      JsonPost('cat/add', e.detail).then(res => {
        if (res.code == 0) {
          wx.showToast({
            title: '已加入购物车',
            icon: 'none',
            duration: 2000
          })
        }
      })
    } else {
      let arr = [Object.assign(this.data.specInfo,this.data.baseInfo)]
      arr[0].shop_price = arr[0].price
      getApp().globalData.shopCartInfo=arr
      if (this.data.goPage == 2) {
        wx.navigateTo({
          url: '/pages/orderPay/orderPay?ifCart=false'
        })

      } else {
        if (this.data.goPage == 3) {
          let data = {
            'goods_id': this.data.detailInfo.goods_id,
            'spec_id': this.data.specInfo.spec_id,
          }
          JsonPost('collage/launch', data).then(res => {
            wx.navigateTo({
              url: '/pages/orderPay/orderPay?ifCart=false&pinId=' + res.data
            })
          })
        } else {
          wx.navigateTo({
            url: '/pages/orderPay/orderPay?sku=' + JSON.stringify(arr) + '&ifCart=false&pinId=' + this.data.pingou_id
          })
        }
      }
    }
  },


  changMbbOL(e) {
    this.setData({
      mengbanBol: false
    });
  },
  calselMbbOL() {
    this.setData({
      mengbanBol: true
    });
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.chudi) {
      let str = "detailInfo.page"
      this.setData({
        jiazai: true,
        [str]: this.data.detailInfo.page + 1
      })
      this.getEvaluate()
    }
  },

  // 实时监控滚动距离顶部的位置
  onPageScroll: function (e) {
    var that = this
    if (e.scrollTop >= that.data.topheight) {
      that.setData({
        onTop: true
      })
    } else if (e.scrollTop < that.data.topheight) {
      that.setData({
        onTop: false
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    if (options.from === 'button') {
      // 来自页面内转发按钮
      let shareObj = {
        title: this.data.baseInfo.goods_name,
        path: "/pages/goodsDetail/goodsDetail?goods_id=" + this.data.detailInfo.goods_id,
        imageUrl: this.data.background[1]
      }
      return shareObj;
    }
  }
})